package com.ruoyi.xysl.service.impl;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.TreeSelect;
import com.ruoyi.xysl.domain.dto.XyslUserDto;
import com.ruoyi.xysl.mapper.SysXyslRoleMapper;
import com.ruoyi.xysl.service.ISysXyslRoleService;
import com.xysl.api.domain.XyslRole;
import com.xysl.api.domain.XyslUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色Service业务层处理
 *
 * @author xysl
 * @date 2025-01-10
 */
@Service
public class SysXyslRoleServiceImpl implements ISysXyslRoleService
{
    @Resource
    private SysXyslRoleMapper sysXyslRoleMapper;

    /**
     * 查询角色
     *
     * @param id 角色主键
     * @return 角色
     */
    @Override
    public XyslRole selectXyslRoleById(Long id)
    {
        return sysXyslRoleMapper.selectXyslRoleById(id);
    }

    /**
     * 查询角色列表
     *
     * @param xyslRole 角色
     * @return 角色
     */
    @Override
    public List<XyslRole> selectXyslRoleList(XyslRole xyslRole)
    {
        return sysXyslRoleMapper.selectXyslRoleList(xyslRole);
    }

    /**
     * 新增角色
     *
     * @param xyslRole 角色
     * @return 结果
     */
    @Override
    public int insertXyslRole(XyslRole xyslRole)
    {
        return sysXyslRoleMapper.insertXyslRole(xyslRole);
    }

    /**
     * 修改角色
     *
     * @param xyslRole 角色
     * @return 结果
     */
    @Override
    public int updateXyslRole(XyslRole xyslRole)
    {
        sysXyslRoleMapper.updateXyslRole(xyslRole);
        // 删除角色与菜单关联
        sysXyslRoleMapper.deleteRoleMenuByRoleId(xyslRole.getId());
        return insertRoleMenu(xyslRole);
    }

    public int insertRoleMenu(XyslRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<Map<String,Object>> list = new ArrayList<>();
        for (Long menuId : role.getMenuIds())
        {
            Map<String,Object> roleMenuMap = new HashMap<>();
            roleMenuMap.put("menuId",menuId);
            roleMenuMap.put("roleId",role.getId());
            list.add(roleMenuMap);
        }
        if (list.size() > 0)
        {
            rows = sysXyslRoleMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 批量删除角色
     * @return 结果
     */
    @Override
    public int deleteXyslRoleByIds(Long[] roleIds)
    {
        for (Long roleId : roleIds)
        {
            if (sysXyslRoleMapper.countUserRoleByRoleId(roleId) > 0)
            {
                throw new ServiceException("角色已分配用户,不能删除");
            }
        }
        // 删除角色与菜单关联
        sysXyslRoleMapper.deleteRoleMenu(roleIds);
        return sysXyslRoleMapper.deleteXyslRoleByIds(roleIds);
    }

    /**
     * 删除角色信息
     *
     * @param id 角色主键
     * @return 结果
     */
    @Override
    public int deleteXyslRoleById(Long id)
    {
        return sysXyslRoleMapper.deleteXyslRoleById(id);
    }

    @Override
    public boolean checkRoleNameUnique(XyslRole role) {
        Long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        XyslRole info = sysXyslRoleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkRoleCodeUnique(XyslRole role) {
        Long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        XyslRole info = sysXyslRoleMapper.checkRoleCodeUnique(role.getRoleCode());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (Long userId : userIds)
        {
            HashMap<String,Object> map = new HashMap<String,Object>();
            map.put("roleId",roleId);
            map.put("userId",userId);
            list.add(map);
        }
        return sysXyslRoleMapper.batchUserRole(list);
    }

    @Override
    public List<XyslUser> selectAllocatedList(XyslUserDto user) {
        return sysXyslRoleMapper.selectAllocatedList(user);
    }

    @Override
    public List<XyslUser> selectUnallocatedList(XyslUserDto user) {
        return sysXyslRoleMapper.selectUnallocatedList(user);
    }


    @Override
    public int cancelAuthUserBath(Long roleId, Long[] userIds) {
        return sysXyslRoleMapper.deleteUserRoleInfos(roleId,userIds);
    }


    @Override
    public List<XyslRole> selectParentRoleList(Long roleId) {
        return sysXyslRoleMapper.selectParentRoleList(roleId);
    }

    @Override
    public List<TreeSelect> buildRoleTreeSelect(List<XyslRole> list) {
        List<XyslRole> roleTrees = buildRoleTree(list);
        return roleTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    public List<XyslRole> buildRoleTree(List<XyslRole> roles) {
        List<XyslRole> returnList = new ArrayList<XyslRole>();
        List<Long> tempList = roles.stream().map(XyslRole::getId).collect(Collectors.toList());
        for (Iterator<XyslRole> iterator = roles.iterator(); iterator.hasNext();)
        {
            XyslRole role = (XyslRole) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(role.getParentId()))
            {
                recursionFn(roles, role);
                returnList.add(role);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = roles;
        }
        return returnList;
    }



    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<XyslRole> list, XyslRole t)
    {
        // 得到子节点列表
        List<XyslRole> childList = getChildList(list, t);
        t.setChildren(childList);
        for (XyslRole tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<XyslRole> getChildList(List<XyslRole> list, XyslRole t)
    {
        List<XyslRole> tlist = new ArrayList<XyslRole>();
        Iterator<XyslRole> it = list.iterator();
        while (it.hasNext())
        {
            XyslRole n = (XyslRole) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<XyslRole> list, XyslRole t)
    {
        return getChildList(list, t).size() > 0;
    }
}
